# import akshare as ak
#
# stock_intraday_em_df = ak.stock_intraday_em(symbol="000001")
# print(stock_intraday_em_df)
import threading
import time
from threading import Thread

import akshare as ak
import datetime
INTERNAL = 10
CACHE_FILE = "s.txt"
# lock = threading.Lock()
class Quant:
    def __init__(self):
        self.running = True
        self.securitys={}
        self.quantBot = None

    def setQuantBot(self,quantBot):
        self.quantBot = quantBot

    def run(self):
        self.read_securitys()
        while self.running:
            # lock.acquire()
            self.run_tick()
            # lock.release()
            time.sleep(INTERNAL)

    def read_basic(self, code):
        print(f"read basic {code}")
        stock_bid_ask_em_df = ak.stock_bid_ask_em(symbol=code)
        # print(stock_bid_ask_em_df)

        self.securitys[code]["code"]=code
        self.securitys[code]["name"] = ""
        self.securitys[code]["last_close"] = stock_bid_ask_em_df.iloc[31].iloc[1]
        self.securitys[code]["today_open"] = stock_bid_ask_em_df.iloc[30].iloc[1]
        self.securitys[code]["high"] = stock_bid_ask_em_df.iloc[28].iloc[1]
        self.securitys[code]["low"] = stock_bid_ask_em_df.iloc[29].iloc[1]

    def run_tick(self):
        print("run tick")
        self.save_securitys()
        for s in list(self.securitys.keys()):
            self.read_basic(s)
            self.read_tick(s)
            last_close = self.securitys[s]["last_close"]
            high = self.securitys[s]["high"]
            low = self.securitys[s]["low"]
            price = self.securitys[s]["price"]
            price_last = self.securitys[s]["price_last"]
            h1 = max(last_close,high)
            l1 = min(last_close,low)
            p1 = h1-l1
            resistance = round(l1+p1*8/9,2)
            support = round(l1+p1*0.5/9,2)

            self.securitys[s]["resistance"] = resistance
            self.securitys[s]["support"] = support

            print(
                f"tick {s} 昨收:{last_close} "
                f"高:{high} 低:{low} h1:{h1} l1:{l1} p1:{round(p1,2)} 阻力:{resistance} 支撑:{support}"
                f" 现价:{price} 前价:{price_last}")
            if price_last<=support and price>support:
                self.quantBot.send_notice(f"{s} 前价:{price_last} 现价：{price} 支撑:{support} 价格上穿支撑，买入")

            if resistance<=price_last and resistance<price:
                self.quantBot.send_notice(f"{s} 前价:{price_last} 现价：{price} 阻力:{resistance} 价格下穿阻力，卖出")

    def save_securitys(self):
        if len(self.securitys)>0:
            with open(CACHE_FILE,mode="w",encoding="utf-8") as f:
                strs = ""
                for s in list(self.securitys.keys()):
                    strs+=s+","
                f.write(strs)

    def read_securitys(self):
        with open(CACHE_FILE, mode="r", encoding="utf-8") as f:
            strs = f.readline()
            code_list = strs.split(",")
            for code in code_list:
                if len(code)>0:
                    self.add_security(code)

    def read_tick(self,code):
        today = time.strftime("%Y-%m-%d", time.localtime())
        # today = '2025-02-14'
        # 读取分时数据
        kline = ak.stock_zh_a_hist_min_em(symbol=code,
                                          start_date=f"{today} 09:30:00",
                                          end_date=f"{today} 15:00:00",
                                          period="1",
                                          adjust="")
        if len(kline)<2:
            return
        self.securitys[code]["price"] = kline.iloc[-1]['收盘']
        self.securitys[code]["price_last"] = kline.iloc[-2]['收盘']

    def run_in_thread(self):
        t = Thread(target=self.run)
        t.start()

    def add_security(self,security):
        # lock.acquire()
        if security in list(self.securitys.keys()):
            return
        else:
            self.securitys[security] = {"code":security,
                                        "name":"",
                                        "last_close":0,
                                        "today_open":0,
                                        "high":0,
                                        "low":0,
                                        "price":0,
                                        "price_last":0
                                        }
        # lock.release()

    def remove_security(self,security):
        # lock.acquire()
        del self.securitys[security]
        # lock.release()